package org.poc.camel;

import java.io.IOException;
import java.io.StringBufferInputStream;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.camel.Exchange;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class InventoryBean {

	private String type;

	public InventoryBean(String type) {
		this.type = type;
	}

	/*
	public String process(String input) throws ParserConfigurationException,
			SAXException, IOException {
		String result = extractItemValue(input);

		return result + this.type;
	}
	*/

	private String extractItemValue(String input)
			throws ParserConfigurationException, SAXException, IOException {
		DocumentBuilderFactory domFactory = DocumentBuilderFactory
				.newInstance();
		domFactory.setNamespaceAware(true);
		DocumentBuilder builder = domFactory.newDocumentBuilder();
		Document doc = builder.parse( new InputSource(new StringReader(input)));

		String result = doc.getElementsByTagName("item").item(0).getFirstChild().getNodeValue();
		return result;
	}
	
	public void process(Exchange exchange) throws ParserConfigurationException, SAXException, IOException{
		
		String body = exchange.getIn().getBody(String.class);
		String value = extractItemValue(body);
		
		exchange.getIn().setBody(value+this.type);
		
	}

}
